package com.smyh.UIM;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.smyh.adapter.AddrItemAdapter;
import com.smyh.cache.MainUIChooseType;
import com.smyh.cache.PreferenceCommon;
import com.smyh.cache.PreferenceSearcheParam;
import com.smyh.cache.UIM.MainCahce;
import com.smyh.common.MinaClientThread;
import com.smyh.database.DataPointDBHelper;
import com.smyh.database.PointInfoDBHelper;
import com.smyh.protcol.CMDUtil;
import com.smyh.server.CommunAsyncTask;
import com.smyh.util.HexStrUtil;

import org.apache.mina.core.buffer.IoBuffer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends FragmentActivity implements OnClickListener {
    private static final String TAG = "MainActivity";

    PopupWindow popupWindow;
    SimpleAdapter popupWindowAdapter;
    List<HashMap<String, Object>> data = new ArrayList<>();
    /**
     * 菜单弹出来时候的菜单项文字
     */
    private String[] names = {"组", "主机·操作", "101参数", "硬件参数", "GRPS参数",
            "版本信息", "点位信息","主机升级"};
    private int[] images = {R.drawable.i1};
    public static Context context;
    private LinearLayout leftMenu;
    private LinearLayout content;

    static ListView list_view;
    static BaseAdapter addrItemAdapter;

    FrameLayout footfm;
    private Fragment hostFragment, deviceFragment, recordFragment, userFragment, currentFragment;
    RadioGroup radioGroup;
    RadioButton host_btn, device_btn, record_btn, user_btn;
    ImageView menu_img;

    public static PointInfoDBHelper pointInfoDb;
    public static DataPointDBHelper dataPointDb;

    /**
     * 搜索条件、按钮
     */
    EditText rf_call_time, rf_wait_time, rf_call_distance, rf_comm_freq, rf_call_chanel;

    public static TextView home_resource;

    Button searchButton, btn_l_on, btn_l_off;
    public static Handler mainHandler;
    /**
     * 搜索条件、按钮
     */

    /**
     * 无限通讯设置
     */
    ImageButton wifiSetBtn;

    boolean wifiSetFlag;

    private LayoutParams leftMenuParams;
    private LayoutParams contentParams;

    // menu完全显示时，留给content的宽度值。
    private static final int menuPadding = 300;
    private ImageView leftBtn;

    // 分辨率
    private int disPlayWidth;

    private boolean mIsShow = false;

    private static final int speed = 1000;
    public boolean isMenu = false;

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = MainActivity.this;
        mainHandler = new Handler();
        initData();
        initView();
        initEvent();
        initServer();
    }


    /**
     * 初始化服务
     */
    private void initServer() {
        new CommunAsyncTask().equals("通讯异步线程监听开始！");
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (MinaClientThread.session == null || !MinaClientThread.session.isConnected()) {
                        //未连接
                        if (wifiSetFlag) {
                            wifiSetFlag = false;
                            wifisetBtnhandler.sendMessage(new Message());
                        }
                    } else {
                        //连接
                        if (!wifiSetFlag) {
                            wifiSetFlag = true;
                            wifisetBtnhandler.sendMessage(new Message());
                        }
                    }
                    try {
                        Thread.sleep(800);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    Handler wifisetBtnhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (!wifiSetFlag) {//未连接
                wifiSetBtn.setImageResource(R.drawable.wifi_set_off);
            } else {
                wifiSetBtn.setImageResource(R.drawable.wifi_set_on);
            }
        }
    };

    private void initEvent() {

        /**
         * 增加搜索条件组件事件：
         */

        rf_call_time.addTextChangedListener(tw1);
        rf_wait_time.addTextChangedListener(tw2);
        rf_call_distance.addTextChangedListener(tw3);
        rf_comm_freq.addTextChangedListener(tw4);
        rf_call_chanel.addTextChangedListener(tw5);

        /**
         * 增加搜索条件组件事件：
         */
        menu_img.setOnClickListener(this);
        searchButton.setOnClickListener(this);
        btn_l_on.setOnClickListener(this);
        btn_l_off.setOnClickListener(this);
        leftBtn.setOnClickListener(this);
        wifiSetBtn.setOnClickListener(this);

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.host_btn:
                        MainUIChooseType.chooseMainType = 1;
                        if (currentFragment == hostFragment) {
                            return;
                        } else {
                            getSupportFragmentManager().beginTransaction().show(hostFragment).hide(deviceFragment)
                                    .hide(recordFragment).hide(userFragment).commit();
                            HostFragment.showCurrentFM();
                            DeviceFragment.hiddenAll();
                            currentFragment = hostFragment;
                            menu_img.setVisibility(View.VISIBLE);
                            data.clear();
                            names = new String[]{"组", "主机·操作", "101参数", "硬件参数", "GRPS参数",
                                    "版本信息", "点位信息","主机升级"};
                            for (int i = 0; i < names.length; i++) {
                                HashMap<String, Object> item = new HashMap<>();
                                item.put("image", images[0]);
                                item.put("name", names[i]);
                                data.add(item);
                            }
                        }
                        break;
                    case R.id.device_btn:
                        MainUIChooseType.chooseMainType = 2;
                        if (currentFragment == deviceFragment) {
                            return;
                        } else {
                            getSupportFragmentManager().beginTransaction().hide(hostFragment).show(deviceFragment)
                                    .hide(recordFragment).hide(userFragment).commit();
                            HostFragment.hiddenAll();
                            DeviceFragment.showCurrentFM();
                            currentFragment = deviceFragment;
                            menu_img.setVisibility(View.VISIBLE);
                            data.clear();
                            names = new String[]{"状态", "参数1", "参数2", "参数3", "参数4",
                                    "参数5","参数6", "操作", "升级"};
                            for (int i = 0; i < names.length; i++) {
                                HashMap<String, Object> item = new HashMap<>();
                                item.put("image", images[0]);
                                item.put("name", names[i]);
                                data.add(item);
                            }
                        }
                        break;
                    case R.id.record_btn:
                        MainUIChooseType.chooseMainType = 3;
                        if (currentFragment == recordFragment) {
                            return;
                        } else {
                            getSupportFragmentManager().beginTransaction().hide(hostFragment).hide(deviceFragment)
                                    .show(recordFragment).hide(userFragment).commit();
                            HostFragment.hiddenAll();
                            DeviceFragment.hiddenAll();
                            currentFragment = recordFragment;
                            menu_img.setVisibility(View.VISIBLE);
                            data.clear();
                            names = new String[]{"主机同步录波", "主机故障录波",
                                    "指示器同步录波", "指示器故障录波", "指示器单波录波"};
                            for (int i = 0; i < names.length; i++) {
                                HashMap<String, Object> item = new HashMap<>();
                                item.put("image", images[0]);
                                item.put("name", names[i]);
                                data.add(item);
                            }
                        }
                        break;
                    case R.id.user_btn:
                        MainUIChooseType.chooseMainType = 4;
                        if (currentFragment == userFragment) {
                            return;
                        } else {
                            getSupportFragmentManager().beginTransaction().hide(hostFragment).hide(deviceFragment)
                                    .hide(recordFragment).show(userFragment).commit();
                            HostFragment.hiddenAll();
                            DeviceFragment.hiddenAll();
                            currentFragment = userFragment;
                            menu_img.setVisibility(View.GONE);
                        }
                        break;
                }
                popupWindowAdapter.notifyDataSetChanged();
            }
        });

    }

    private void initData() {
        MainCahce.deviceInfos = new HashMap<>();
        PreferenceCommon.sPreferences = getSharedPreferences(PreferenceCommon.STORE_NAME, MODE_PRIVATE);
        pointInfoDb = new PointInfoDBHelper(this);
        dataPointDb = new DataPointDBHelper(this);
    }

    Long time = 0l;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            AlertDialog.Builder aa = new AlertDialog.Builder(this);
            aa.setTitle("消息提示").setMessage("确认退出？")
//            aa.setIcon(R.drawable.icon);
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            MainActivity.this.finish();
                        }
                    }).setNegativeButton("取消", null).create();
            aa.show();

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 初始化视图 TODO
     */
    private void initView() {
        disPlayWidth = getWindowManager().getDefaultDisplay().getWidth();
        home_resource = (TextView) findViewById(R.id.home_resource);
        leftMenu = (LinearLayout) findViewById(R.id.leftMenu);
        content = (LinearLayout) findViewById(R.id.content);
        list_view = (ListView) findViewById(R.id.list_view);
        footfm = (FrameLayout) findViewById(R.id.footfm);
        radioGroup = (RadioGroup) findViewById(R.id.radio_group);
        host_btn = (RadioButton) findViewById(R.id.host_btn);
        device_btn = (RadioButton) findViewById(R.id.device_btn);
        record_btn = (RadioButton) findViewById(R.id.record_btn);
        user_btn = (RadioButton) findViewById(R.id.user_btn);
        leftBtn = (ImageView) findViewById(R.id.leftBtn);
        menu_img = (ImageView) findViewById(R.id.menu_img);

        /**PopupWindow的界面*/
        View contentView = getLayoutInflater()
                .inflate(R.layout.gridview_menu, null);
        /**网格布局界面*/
        GridView gridView = (GridView) contentView.findViewById(R.id.gridView);
        /**设置网格布局的适配器*/
        for (int i = 0; i < names.length; i++) {
            HashMap<String, Object> item = new HashMap<>();
            item.put("image", images[0]);
            item.put("name", names[i]);
            data.add(item);
        }
        popupWindowAdapter = new SimpleAdapter(MainActivity.this, data,
                R.layout.grid_item, new String[]{"image", "name"},
                new int[]{R.id.imageView, R.id.textView});
        gridView.setAdapter(popupWindowAdapter);
        /**设置网格布局的菜单项点击时候的Listener*/
        gridView.setOnItemClickListener(new ItemClickListener());
        /**初始化PopupWindow*/
        popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);// 取得焦点
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        /**设置PopupWindow弹出和退出时候的动画效果*/
        popupWindow.setAnimationStyle(R.style.animation);

        /**
         * 搜索条件加载组件
         */
        rf_call_time = (EditText) findViewById(R.id.rf_call_time);
        rf_wait_time = (EditText) findViewById(R.id.rf_wait_time);
        rf_call_distance = (EditText) findViewById(R.id.rf_call_distance);
        rf_comm_freq = (EditText) findViewById(R.id.rf_comm_freq);
        rf_call_chanel = (EditText) findViewById(R.id.rf_call_chanel);
        if (PreferenceCommon.sPreferences != null) {
            rf_call_time.setText("" + PreferenceCommon.sPreferences.getInt(PreferenceSearcheParam.RF_CALL_TIME, 5));
            rf_wait_time.setText("" + PreferenceCommon.sPreferences.getInt(PreferenceSearcheParam.RF_WAIT_TIME, 30));
            rf_call_distance.setText("" + PreferenceCommon.sPreferences.getInt(PreferenceSearcheParam.RF_CALL_DISTANCE, 5));
            rf_comm_freq.setText("" + PreferenceCommon.sPreferences.getInt(PreferenceSearcheParam.RF_COMM_FREQ, 8));
            rf_call_chanel.setText("" + PreferenceCommon.sPreferences.getInt(PreferenceSearcheParam.RF_CALL_CHANEL, 31));
        }

        searchButton = (Button) findViewById(R.id.searchButton);
        btn_l_on = (Button) findViewById(R.id.btn_l_on);
        btn_l_off = (Button) findViewById(R.id.btn_l_off);

        /**
         * 搜索条件加载组件
         */
        wifiSetBtn = (ImageButton) findViewById(R.id.wifi_set_btn);

        hostFragment = new HostFragment();
        deviceFragment = new DeviceFragment();
        recordFragment = new RecordFragment();
        userFragment = new UserFragment();
        currentFragment = hostFragment;

        getSupportFragmentManager().beginTransaction().add(R.id.footfm, hostFragment).add(R.id.footfm, deviceFragment).hide(deviceFragment)
                .add(R.id.footfm, recordFragment).hide(recordFragment).add(R.id.footfm, userFragment).hide(userFragment).commit();
        addrItemAdapter = new AddrItemAdapter();
        list_view.setAdapter(addrItemAdapter);
        leftMenuParams = (LayoutParams) leftMenu.getLayoutParams();
        contentParams = (LayoutParams) content.getLayoutParams();
        leftMenuParams.width = disPlayWidth - menuPadding;
        contentParams.width = disPlayWidth;

        showMenu(mIsShow);
    }

    static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            addrItemAdapter.notifyDataSetChanged();
        }
    };

    public static void refreshDeviceList() {
        handler.sendMessage(new Message());
    }

    private final class ItemClickListener implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            MainUIChooseType.chooseSubType = position+1;
            if (popupWindow.isShowing()) {
                switch (MainUIChooseType.chooseMainType) {
                    case 1:
                        HostFragment.setCurrentfm(position);
                        break;
                    case 2:
                        DeviceFragment.setCurrentfm(position);
                        break;
                    case 3:
                        RecordFragment.setCurrentfm(position);
                        break;
                }
                popupWindow.dismiss();//关闭
            }
        }
    }

    /**
     * 显示界面 TODO
     */
    private void showMenu(boolean isShow) {
        if (isShow) {
            mIsShow = true;
            leftMenuParams.leftMargin = 0;
        } else {
            mIsShow = false;
            leftMenuParams.leftMargin = 0 - leftMenuParams.width;
        }
        leftMenu.setLayoutParams(leftMenuParams);
    }

    /**
     * TODO 控制左侧View
     */
    class showMenuAsyncTask extends AsyncTask<Integer, Integer, Integer> {

        @Override
        protected Integer doInBackground(Integer... params) {
            int leftMargin = leftMenuParams.leftMargin;
            while (true) {
                leftMargin += params[0];
                if (params[0] >= 0 && leftMargin >= 0) {
                    leftMargin = 0;
                    break;
                } else if (params[0] < 0 && leftMargin <= -leftMenuParams.width) {
                    leftMargin = -leftMenuParams.width;
                    break;
                }
                publishProgress(leftMargin);
                try {
                    Thread.sleep(30);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return leftMargin;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            leftMenuParams.leftMargin = values[0];
            leftMenu.setLayoutParams(leftMenuParams);
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
            leftMenuParams.leftMargin = result;
            leftMenu.setLayoutParams(leftMenuParams);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.leftBtn:
                if (isMenu) {
                    isMenu = false;
                    new showMenuAsyncTask().execute(-speed);
                } else {
                    isMenu = true;
                    new showMenuAsyncTask().execute(speed);
                }
                break;
            case R.id.content:
                break;
            case R.id.searchButton:
                if (MinaClientThread.session != null && MinaClientThread.session.isConnected()) {
                    IoBuffer buffer = CMDUtil.callDevicesParam();
                    MinaClientThread.session.write(buffer).awaitUninterruptibly();
                    Toast.makeText(context, "指令下发！", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "没有通讯！", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_l_on:
                //亮灯按钮
                if (MinaClientThread.session != null && MinaClientThread.session.isConnected()) {
                    byte[] deviceAddrBytes = HexStrUtil.hexStr2Bytes(MainCahce.chooseDeviceAddr);
                    IoBuffer buffer = CMDUtil.on_offLight(deviceAddrBytes, true);
                    MinaClientThread.session.write(buffer);
                    Toast.makeText(context, "亮灯灯指令下发", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_l_off:
                //灭灯按钮
                if (MinaClientThread.session != null && MinaClientThread.session.isConnected()) {
                    byte[] deviceAddrBytes = HexStrUtil.hexStr2Bytes(MainCahce.chooseDeviceAddr);
                    IoBuffer buffer = CMDUtil.on_offLight(deviceAddrBytes, false);
                    MinaClientThread.session.write(buffer);
                    Toast.makeText(context, "灭灯指令下发", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.wifi_set_btn: {
                Intent intent = new Intent(this, WifiSetActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.menu_img: {
                /**设置PopupWindow弹出后的位置*/
                popupWindow.showAtLocation(footfm, Gravity.BOTTOM, 0, 0);
            }
            default:
                break;
        }
    }

    /**
     * 搜索条件文本框事件
     */
    TextWatcher tw1 = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            SharedPreferences.Editor editor = PreferenceCommon.sPreferences.edit();
            String key = PreferenceSearcheParam.RF_CALL_TIME;

            try {
                String valueS = s.toString();
                editor.putInt(key, Integer.parseInt(valueS));
                editor.commit();

            } catch (Exception e) {

            }
        }
    };

    TextWatcher tw2 = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

            SharedPreferences.Editor editor = PreferenceCommon.sPreferences.edit();
            String key = PreferenceSearcheParam.RF_WAIT_TIME;

            try {
                String valueS = s.toString();
                editor.putInt(key, Integer.parseInt(valueS));
                editor.commit();

            } catch (Exception e) {

            }
        }
    };

    TextWatcher tw3 = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

            SharedPreferences.Editor editor = PreferenceCommon.sPreferences.edit();
            String key = PreferenceSearcheParam.RF_CALL_DISTANCE;

            try {
                String valueS = s.toString();
                editor.putInt(key, Integer.parseInt(valueS));
                editor.commit();

            } catch (Exception e) {

            }
        }
    };

    TextWatcher tw4 = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

            SharedPreferences.Editor editor = PreferenceCommon.sPreferences.edit();
            String key = PreferenceSearcheParam.RF_COMM_FREQ;

            try {
                String valueS = s.toString();
                editor.putInt(key, Integer.parseInt(valueS));
                editor.commit();

            } catch (Exception e) {

            }
        }
    };

    TextWatcher tw5 = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

            SharedPreferences.Editor editor = PreferenceCommon.sPreferences.edit();
            String key = PreferenceSearcheParam.RF_CALL_CHANEL;

            try {
                String valueS = s.toString();
                editor.putInt(key, Integer.parseInt(valueS));
                editor.commit();

            } catch (Exception e) {

            }
        }
    };

}
